package com.ruoyi.system.wnjk.listener;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.RedisKeyExpiredEvent;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class OrderExpireListener {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    /**
     * 处理 Redis 键过期事件
     */
    @EventListener
    public void handleKeyExpiration(RedisKeyExpiredEvent<Object> event) {
        String expiredKey = new String(event.getId());
        if (expiredKey.startsWith("order:")) {
            // 获取订单信息
            Map<Object, Object> orderData = redisTemplate.opsForHash().entries(expiredKey);
            String date = (String) orderData.get("date");
            String period = (String) orderData.get("period");
            
            // 回滚库存
            String inventoryKey = "inventory:" + date + ":" + period;
            redisTemplate.opsForHash().increment(inventoryKey, "available", 1);
        }
    }
}